<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.title"
          placeholder="请输入文章标题"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        stripe
        size="large"
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="a_id"
          label="ID"
          width="55"
          align="center"
          type="index"
        ></el-table-column>
        <!-- 标题-->
        <el-table-column
          prop="title"
          label="文章标题"
          width="130"
          align="center"
        ></el-table-column>
        <!-- 内容 -->
        <el-table-column
          prop="content"
          label="文章内容"
          width="130"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createdAt"
          label="注册时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updatedAt"
          label="更新时间"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :icon="EditPen"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >

            <el-popconfirm
              title="确定要删除此文章"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      title="文章编辑"
      width="35%"
      :before-close="cancel"
    >
      <div>
        <el-scrollbar height="50vh">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            status-icon
          >
            <el-form-item label="文章标题" prop="a_title">
              <el-input v-model="ruleForm.a_title" @input="checkS_name" />
            </el-form-item>
            <el-form-item label="文章内容" prop="a_content">
              <el-input v-model="ruleForm.a_content" />
            </el-form-item>
            <el-form-item label="文章类型" prop="a_category">
              <el-input v-model="ruleForm.a_category" />
            </el-form-item>
            <!-- <el-form-item label="用户状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                  <el-radio :label="0">停用</el-radio>
                  <el-radio :label="1">正常</el-radio>
                </el-radio-group>
              </el-form-item> -->
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >更新</el-button
          >
          <!-- <el-button @click="resetForm(ruleFormRef)">重置表单</el-button> -->
          <el-button @click="cancel">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification, ElMessage } from "element-plus";
import { EditPen, Search } from "@element-plus/icons-vue";
// import moment from "moment";
import { IMG_URL } from "@/utils/imgStatic";

const fileList = ref([]);

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);
//重置表单
// const resetForm = (formEl) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

//取消表单
const cancel = () => {
  centerDialogVisible.value = false;
  fileList.value = [];
};

const ruleForm = reactive({
  articleId: "",
  title: "",
  // password: "",
  content: "",
});
const rules = reactive({
  title: [
    {
      required: true,
      message: "请输入标题名",
      trigger: ["blur", "change"],
    },
    {
      pattern: /^\S*$/, // 正则表达式校验用户名，不允许空格
      message: "标题名中不能有空格",
      trigger: ["blur", "change"],
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验用户名，只允许字母、数字和下划线
    //   message: "用户名只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  content: [
    {
      required: true,
      message: "请输入文章内容",
      trigger: ["blur", "change"],
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
const query = reactive({
  title: "",
  currentPage: 1,
  pageSize: 4, //每页显示的数量
});
const tableData = ref([]);
const totalCount = ref(0);
// 获取表格所有数据
const getData = () => {
  request
    .request({
      url: "/article/getAllArticle",
      method: "get",
      params: {
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
    })
    .then((res) => {
      console.log(res);
      tableData.value = res.data.data.rows; // 直接赋值
      totalCount.value = res.data.data.count; // 如果需要总数
    })
    .catch((e) => {
      console.log(e);
    });
};
getData();
//条件查询（角色、用户名）
// 初次加载数据
// 查询操作
const handleSearch = () => {
  // 将当前页设为1以便从第一页开始
  query.currentPage = 1;
  request
    .request({
      url: "/article/getArticle",
      params: {
        title: query.title,
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
      method: "get",
    })
    .then((res) => {
      // 获取当前页的数据
      tableData.value = res.data.data.rows; // 直接赋值
      totalCount.value = res.data.data.count; // 如果需要总数
    })
    .catch((e) => {
      console.log(e);
    });
};
// 分页导航
const handleCurrentChange = (val) => {
  query.currentPage = val;
  getData();
  // console.log(val);
};
// 删除操作
const handleDelete = (index, row) => {
  request
    .request({
      url: "/article/deleteArticle",
      params: {
        articleId: row.articleId, // 使用行数据中的 userId
      },
      method: "get",
    })
    .then((res) => {
      // 删除成功后，更新表格数据
      tableData.value.splice(index, 1); // 从表格中移除删除的行
      totalCount.value -= 1; // 更新总记录数
    })
    .catch((e) => {
      console.log(e);
    });
};
//修改操作
const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.userId = row.userId;
  ruleForm.username = row.username;
  // ruleForm.password = row.password; // 如果需要更新密码，请取消注释
  ruleForm.email = row.email;
  ruleForm.phone = row.phone;
  ruleForm.sex = row.sex;
  ruleForm.role = row.role;
  ruleForm.picture = row.picture;
  fileList.value.push({
    url: `${IMG_URL}${row.picture}`,
  });
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value) => {
      formData.append("file", value.raw);
    });
    formData.append("userId", ruleForm.userId);
    formData.append("username", ruleForm.username);
    formData.append("password", ruleForm.password);
    formData.append("email", ruleForm.email);
    formData.append("phone", ruleForm.phone);
    formData.append("role", ruleForm.role);
    formData.append("sex", ruleForm.sex);
    formData.append("picture", ruleForm.picture);
    if (valid) {
      try {
        const response = await request.request({
          url: "/user/updateUser",
          method: "POST", // 使用 POST 方法
          data: formData,
        });
        ElNotification({
          title: "更新成功",
          message: response.data.message,
          type: "success",
        });
        // 更新表格中的数据
        // ... 更新逻辑
      } catch (error) {
        ElNotification({
          title: "更新失败",
          message: error.response?.data?.message || "请重试",
          type: "error",
        });
      }
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
        type: "error",
      });
    }
  });
};
//检查修改的用户是否重复
const checkS_name = async () => {};
</script>
  
  <style>
.hidden .el-upload--picture-card {
  display: none;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
  